package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.adapter.GiftAdapter;
import com.jiaoyou.baojian.adapter.MessageAdapter;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.agora.ChannelMsg;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.CallResponse;
import com.jiaoyou.baojian.entity.GiftEntity;
import com.jiaoyou.baojian.entity.LocalMessageEntity;
import com.jiaoyou.baojian.entity.MessageEntity;
import com.jiaoyou.baojian.entity.RoomEntity;
import com.jiaoyou.baojian.entity.response.RoomItemResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.BaofangCallback2;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

import static io.agora.rtc.Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
import static io.agora.rtc.Constants.CLIENT_ROLE_AUDIENCE;
import static io.agora.rtc.Constants.CLIENT_ROLE_BROADCASTER;

public class RoomActivity extends BaseActivity implements BaseQuickAdapter.OnItemLongClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.header)
    ImageView header;
    @BindView(R.id.username)
    TextView username;
    @BindView(R.id.usersum)
    TextView usersum;
    @BindView(R.id.mute)
    ImageView mute;
    @BindView(R.id.quit)
    ImageView quit;
    @BindView(R.id.first)
    TextView first;
    @BindView(R.id.second)
    TextView second;
    @BindView(R.id.third)
    TextView third;
    @BindView(R.id.msg_list)
    RecyclerView msgList;
    @BindView(R.id.btn)
    ImageView btn;
    @BindView(R.id.gifts)
    RecyclerView gifts;
    @BindView(R.id.msg)
    EditText msg;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.msg_send_layout)
    LinearLayout msgSendLayout;

    private RoomItemResponse roomItemResponse;
    private boolean muteOn = false;
    private MessageAdapter messageAdapter;
    private GiftAdapter giftAdapter;
    private List<MessageEntity> messageList;
    private List<GiftEntity> giftList;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        roomItemResponse = (RoomItemResponse) getIntent().getExtras().getSerializable("room");
        if(roomItemResponse == null){
            toast("数据获取错误");
            onBackPressed();
            return;
        }

        needOtto();

        isCallBusy = true;

        if(!isMyRoom()){
            waiting("进入包房...");
            Api.getInstance().roomUserEnter(roomItemResponse.room.id, new BaofangCallback<RoomEntity>() {
                @Override
                public void onFailure(Call call, Throwable t) {
                    stopWaiting();
                    finish();
                    toast("进入包房错误：" + t.getLocalizedMessage());
                }

                @Override
                public void onSuccess(RoomEntity o) {
                    stopWaiting();
                    init();
                }
            });
        } else {
            init();
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_room;
    }

    public void init() {
        if(isMyRoom()){
            msgSendLayout.setVisibility(View.GONE);
            gifts.setVisibility(View.GONE);
            btn.setVisibility(View.GONE);
        } else {
            msgSendLayout.setVisibility(View.GONE);
            gifts.setVisibility(View.VISIBLE);
            btn.setVisibility(View.VISIBLE);
        }

        username.setText(roomItemResponse.userInfo.nickname);
        Utils.showImage(RoomActivity.this, roomItemResponse.userInfo.avatar, header);

        messageList = new ArrayList<>();
        messageAdapter = new MessageAdapter();
        msgList.setLayoutManager(new LinearLayoutManager(this));
        msgList.setAdapter(messageAdapter);
        messageAdapter.setNewData(messageList);
        messageAdapter.setEmptyView(getMsgEmptyView());
        messageAdapter.notifyDataSetChanged();
        giftList = new ArrayList<>();
        giftAdapter = new GiftAdapter();
        LinearLayoutManager giftLinearLayoutManager = new LinearLayoutManager(this);
        giftLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        gifts.setLayoutManager(giftLinearLayoutManager);
        gifts.setAdapter(giftAdapter);
        giftAdapter.setNewData(giftList);
        giftAdapter.setEmptyView(getEmptyView());
        giftAdapter.notifyDataSetChanged();
        giftAdapter.setOnItemLongClickListener(this);
        giftAdapter.setOnItemClickListener(this);

        enterTribe();
        enterLive();

        getGiftList();

        handler = new Handler();
        handler.postDelayed(heartBeat, 15000);
    }

    private View getMsgEmptyView(){
        TextView textView = new TextView(this);
        textView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(getResources().getColor(R.color.main_gray));
        textView.setText("土豪们送的礼物会在这里显示哦~");
        return textView;
    }

    private View getEmptyView() {
        TextView textView = new TextView(this);
        textView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        textView.setGravity(Gravity.CENTER);
        textView.setText("加载中");
        return textView;
    }

    private void getGiftList() {
        Api.getInstance().getGiftList(new BaofangCallback2<GiftEntity>(){

            @Override
            public void onFailure(Call<BaseResponse<GiftEntity>> call, Throwable t) {

            }

            @Override
            public void onSuccess(List<GiftEntity> giftEntities) {
                giftList.addAll(giftEntities);
                giftAdapter.notifyDataSetChanged();
            }
        });
    }

    //进入群聊
    private void enterTribe() {
        AgoraHelper.getInstance().agoraAPI.channelJoin(roomItemResponse.room.voiceConferenceId);

        if(!isMyRoom()){
            LocalMessageEntity localMessageEntity = LocalMessageEntity.userEnter(
                    getLoginResponse().user.id,
                    getLoginResponse().userInfo.nickname,
                    getLoginResponse().userInfo.avatar);
            AgoraHelper.getInstance().agoraAPI.messageChannelSend(roomItemResponse.room.voiceConferenceId, getGson().toJson(localMessageEntity), "");
        }
    }

    @Subscribe
    public void onEvent(Event event){
        if(event.event.equals(Event.AGORA_MSG_CHANNEL_RECEIVE)){
            ChannelMsg channelMsg = getGson().fromJson(event.content, ChannelMsg.class);
            if(channelMsg.channelId.equals(roomItemResponse.room.voiceConferenceId)) {
                LocalMessageEntity localMessageEntity = getGson().fromJson(channelMsg.msg, LocalMessageEntity.class);
                addMsg(localMessageEntity.uid, localMessageEntity);
            }
        } else if(event.event.equals(Event.AGORA_CHANNEL_JOIN_FAILED)){
            if(event.content.equals(roomItemResponse.room.voiceConferenceId)){
                toast("网络错误，请重新进入包房");
                finish();
            }
        }
    }

    private void addMsg(int id, LocalMessageEntity localMessageEntity) {
        boolean isMine = (id == getLoginResponse().user.id);
        MessageEntity messageEntity = new MessageEntity();
        switch(localMessageEntity.type){
            case 2:{
                String username = localMessageEntity.name;
                String avatar = localMessageEntity.avatar;
                int giftid = localMessageEntity.gift_id;
                messageEntity.msg = (isMine ? "你" : username) + "送了一个" + getGiftName(giftid);
                messageEntity.type = 2;
                messageEntity.avatar = avatar;
                messageList.add(messageEntity);
                messageAdapter.notifyDataSetChanged();
                msgList.smoothScrollToPosition(messageList.size());
                Utils.showGiftAnimation(this, giftid, giftList);
            }
                break;
            case 1:
            case 3:{
                String username = localMessageEntity.name;
                String avatar = localMessageEntity.avatar;
                String content = localMessageEntity.content;
                messageEntity.type = 1;
                messageEntity.msg = content;
                messageEntity.username = username;
                messageEntity.avatar = avatar;
                messageList.add(messageEntity);
                messageAdapter.notifyDataSetChanged();
                msgList.smoothScrollToPosition(messageList.size());
            }
            break;
        }
    }

    /**
     * 进入直播
     */
    private void enterLive() {
        rtcEngine.setChannelProfile(CHANNEL_PROFILE_LIVE_BROADCASTING);
        if(isMyRoom()) {
            rtcEngine.setClientRole(CLIENT_ROLE_BROADCASTER, "");
        }
        else {
            rtcEngine.setClientRole(CLIENT_ROLE_AUDIENCE, "");
        }
        rtcEngine.enableAudio();
//        rtcEngine.setLogFile(Environment.getExternalStorageDirectory()
//                + File.separator + getPackageName() + "/log/agora-rtc.log");
        rtcEngine.setEnableSpeakerphone(false);
//        rtcEngine.setSpeakerphoneVolume(255); //0-255
        Api.getInstance().getRoomKey(getLoginResponse().user.id + "", roomItemResponse.room.voiceConferenceId,
                new BaofangCallback<CallResponse>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                finish();
                toast("进入包房错误：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(CallResponse res) {
                if(isDestroyed)
                    return;
                rtcEngine.joinChannel(res.agoraChannelKey, roomItemResponse.room.voiceConferenceId, "", getLoginResponse().user.id);
            }
        });
    }

    private boolean isMyRoom(){
        return getLoginResponse().userInfo.userId == roomItemResponse.room.userId;
    }

    @OnClick({R.id.header, R.id.username, R.id.usersum, R.id.mute, R.id.quit, R.id.first, R.id.second, R.id.third, R.id.btn, R.id.send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.header:
            case R.id.usersum:
            case R.id.username:
                if(isMyRoom())
                    return;
                Intent intent = new Intent(this, UserInfoActivity.class);
                intent.putExtra("userinfo", roomItemResponse.userInfo);
                startActivity(intent);
                break;
            case R.id.mute:
                if(isMyRoom()){
                    if(muteOn) {
                        muteOn = false;
//                        rtcEngine.setEnableSpeakerphone(false);
                        rtcEngine.muteLocalAudioStream(false);
                        mute.setImageResource(R.drawable.btn_mute_off);
                    } else {
                        muteOn = true;
//                        rtcEngine.setEnableSpeakerphone(true);
                        rtcEngine.muteLocalAudioStream(true);
                        mute.setImageResource(R.drawable.btn_mute_on);
                    }
                    return;
                }
                if(muteOn) {
                    muteOn = false;
                    rtcEngine.muteAllRemoteAudioStreams(false);
                    mute.setImageResource(R.drawable.btn_mute_off);
                } else {
                    muteOn = true;
                    rtcEngine.muteAllRemoteAudioStreams(true);
                    mute.setImageResource(R.drawable.btn_mute_on);
                }
                break;
            case R.id.quit:
                onBackPressed();
                break;
            case R.id.first:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.second:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.third:
                startActivity(UserInfoActivity.class);
                break;
            case R.id.btn:
                if(gifts.getVisibility() == View.VISIBLE){
                    btn.setImageResource(R.drawable.btn_sendgift_selector);
                    gifts.setVisibility(View.GONE);
                    msgSendLayout.setVisibility(View.VISIBLE);
                    msg.requestFocus();
                    Utils.showKeyboard(gifts, this);
                } else {
                    btn.setImageResource(R.drawable.btn_write_selector);
                    gifts.setVisibility(View.VISIBLE);
                    msgSendLayout.setVisibility(View.GONE);
                    Utils.hideKeyboard(gifts, this);
                }
                break;
            case R.id.send:
                String s = msg.getEditableText().toString();
                if(TextUtils.isEmpty(s))
                    return;
                LocalMessageEntity localMessageEntity =
                        LocalMessageEntity.normalMsg(getLoginResponse().user.id,
                                getLoginResponse().userInfo.nickname,
                                getLoginResponse().userInfo.avatar,
                                s);
                AgoraHelper.getInstance().agoraAPI.messageChannelSend(roomItemResponse.room.voiceConferenceId, getGson().toJson(localMessageEntity), "");
//                addMsg(Utils.getUser().id, localMessageEntity);
                msg.setText("");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(handler != null) {
            handler.removeCallbacks(heartBeat);
        }
        //退出
        if (isMyRoom()) {
            Api.getInstance().exitRoom(new BaofangCallback<String>() {
                @Override
                public void onFailure(Call call, Throwable t) {
                }

                @Override
                public void onSuccess(String s) {
                }
            });
        } else {
            Api.getInstance().exitRoom(roomItemResponse.room.id, new BaofangCallback() {
                @Override
                public void onFailure(Call call, Throwable t) {

                }

                @Override
                public void onSuccess(Object o) {

                }
            });
            LocalMessageEntity localMessageEntity =
                    LocalMessageEntity.userLeave(getLoginResponse().user.id,
                            getLoginResponse().userInfo.nickname,
                            getLoginResponse().userInfo.avatar);
            AgoraHelper.getInstance().agoraAPI.messageChannelSend(roomItemResponse.room.voiceConferenceId, getGson().toJson(localMessageEntity), "");
        }
        rtcEngine.leaveChannel();
        AgoraHelper.getInstance().agoraAPI.channelLeave(roomItemResponse.room.voiceConferenceId);
        isCallBusy = false;
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        GiftEntity giftEntity = giftList.get(position);
        giveGift(giftEntity);
        return true;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        final GiftEntity giftEntity = giftList.get(position);
        showYesOrNoDialog("赠送礼物" + giftEntity.getDescription(), "取消", "赠送", new YesOrNoDialog.OnClickListener() {
            @Override
            public void onLeftClick() {
            }

            @Override
            public void onRightClick() {
                giveGift(giftEntity);
            }
        });
    }

    private void giveGift(GiftEntity giftEntity){
        final LocalMessageEntity localMessageEntity = LocalMessageEntity.giveGift(getLoginResponse().user.id, getLoginResponse().userInfo.nickname, getLoginResponse().userInfo.avatar, giftEntity.getId(), giftEntity.getImg(), giftEntity.getDescription());
        Api.getInstance().giveRoomGift(roomItemResponse.room.id, giftEntity.getId(), 1, new BaofangCallback() {
            @Override
            public void onFailure(Call call, Throwable t) {
                toast("余额不足，请充值");
                showYesOrNoDialog("余额不足，请充值", "取消", "充值", new YesOrNoDialog.OnClickListener() {
                    @Override
                    public void onLeftClick() {

                    }

                    @Override
                    public void onRightClick() {
                        RechargeActivity.show(RoomActivity.this);
                    }
                });
            }

            @Override
            public void onSuccess(Object o) {
//                addMsg(Utils.getUser().id, localMessageEntity);
                AgoraHelper.getInstance().agoraAPI.messageChannelSend(roomItemResponse.room.voiceConferenceId + "", getGson().toJson(localMessageEntity), "");
            }
        });
    }

    private String getGiftName(int id){
        for(GiftEntity giftEntity : giftList){
            if(giftEntity.getId() == id)
                return giftEntity.getDescription();
        }
        return "";
    }

    private Runnable heartBeat = new Runnable() {
        @Override
        public void run() {
            if(isMyRoom()){
                Api.getInstance().roomHeartbeatZhubo(roomItemResponse.room.id, new BaofangCallback<Integer>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        toast("包房出错：" + t.getLocalizedMessage());
                        finish();
                    }

                    @Override
                    public void onSuccess(Integer o) {

                    }
                });
            } else {
                Api.getInstance().roomUserHeartbeat(roomItemResponse.room.id, new BaofangCallback<Integer>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        toast("包房出错：" + t.getLocalizedMessage());
                        finish();
                    }

                    @Override
                    public void onSuccess(Integer o) {

                    }
                });
            }

            handler.postDelayed(heartBeat, 15000);
        }
    };

    @Override
    public void onBackPressed() {
        showYesOrNoDialog("确定退出包房？", new YesOrNoDialog.OnClickListener(){
            @Override
            public void onLeftClick() {

            }

            @Override
            public void onRightClick() {
                RoomActivity.super.onBackPressed();
            }
        });
    }
}
